var devId = getQueryString("id");
$(function () {
    $("#jqGrid").Grid({
        url: '../sparepartdev/devlist?devId=' + devId,
        colModel: [
            {label: '备件编码', name: 'PART_CODE', width: 80},
            {label: 'ERP编码', name: 'ERP_CODE', width: 80},
            {label: '名称', name: 'NAME', index: 'NAME', width: 120},
            {label: '规格', name: 'SPEC', index: 'SPEC', width: 120},
            {label: '生产厂家', name: 'PRODUCOR', index: 'PRODUCOR', width: 120},
            {label: '使用单位', name: 'USE_UNIT', index: 'USE_UNIT', width: 80},
            {label: '库存数量', name: 'STOCK_NUM', index: 'STOCK_NUM', width: 80},
            {label: 'id', name: 'ID', index: 'ID', key: true, hidden: true},
            {
                label: '审核状态', name: 'CHECK_FLAG', index: 'CHECK_FLAG', width: 80, formatter: function (value) {
                    return sysEnums.CHECK_FLAG[value];
                }
            }
        ],
        loadComplete: function () {
            var res = $("#jqGrid").jqGrid('getGridParam', 'records');
            if(res === 0) {
                //vm.getSparePart();
            }
        }
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        sparePartDev: {},
        ruleValidate: {
            spareId: [
                {required: true, message: '备件不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: ''
        },
        spareList: [],
        sparePart: {},
        picUrl:'',
        sourceList:enumsToList('SPARE_RESOURCES_TYPE')
    },
    methods: {
        query: function () {
            vm.reload();
        },
        // add: function () {
        //     vm.showList = false;
        //     vm.title = "新增";
        //     vm.sparePartDev = {id: '', delFlag: 1, devId: devId, checkFlag: 0};
        //     vm.getDropDown();
        // },
        // update: function (event) {
        //     var id = getSelectedRow("#jqGrid");
        //     if (id == null) {
        //         return;
        //     }
        //     vm.showList = false;
        //     vm.title = "修改";
        //
        //     vm.getInfo(id);
        // },
        saveOrUpdate: function (event) {
            var url = vm.sparePartDev.id == (null || '') ? "../sparepartdev/save" : "../sparepartdev/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.sparePartDev),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartdev/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../sparepartdev/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.sparePartDev = r.sparePartDev;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            // vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        getDropDown: function () {
            Ajax.request({
                url: "../sparepart/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.spareList = r.list;
                }
            });
        },
        getBySpareId: function (item) {
            vm.sparePart = item;
            vm.sparePartDev.spareId = item.id;
        },
        review: function () { //审核
            // 记录必选
            var sparePartDevRecords = getSelectedRowDatas("#jqGrid");
            if(sparePartDevRecords && sparePartDevRecords.length == 0){
                return alert('请选择记录后再进行审核');
            }
            // 已审核过的不允许再次审核
            let sparePartDevRecordIdList = [];
            for (let i = 0; i < sparePartDevRecords.length; i++) {
                if(sparePartDevRecords[i].CHECK_FLAG == "已审核"){
                    return alert('请移除审核过的记录后再进行审核');
                }
                sparePartDevRecordIdList.push(sparePartDevRecords[i].ID);
            }
            confirm('确定要审核选中的记录？', function () {
                vm.sparePartDev.checkFlag = 1;
                Ajax.request({
                    url: '../sparepartdev/batchReview',
                    params: JSON.stringify(sparePartDevRecordIdList),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        //显示备件列表-物料编码
        getSparePart: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: '../spare/sparePartQuery.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSelectedSpareParts();
                    if (res && res.length == 0) {
                        alert("请至少选择一条备件记录");
                    } else {
                        layer.close(index);
                        let correlationParam = {devId: devId, sparePartIdList: res};
                        Ajax.request({
                            url: "../sparepartdev/save",
                            params: JSON.stringify(correlationParam),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            }
                        });
                    }
                }
            })
        },
        insert:function(){
            vm.showList = false;
            vm.title = "新增";
            vm.sparePart = {id: '', delFlag: 1, partCode: '', devCode: '', storeId: '',isChange:1};
            var total = 0;
            Ajax.request({
                url: "../sparepart/count",
                async: false,
                successCallback: function (r) {
                    total = r.total + 1;
                    vm.sparePart.partCode = 'SPARE_CODE_' + (Array(6).join(0) + total).slice(-6);
                }
            });
            // }

        },
        sava:function () {
            var url ="../sparepart/save";
            var num=0;
                var flag= /^[a-zA-Z]+$/.test(vm.sparePart.name)
                if(flag==true){
                    alert('名称不能为全字母!');
                    return
                }
                if (vm.sparePart.scrapNum<0){
                    alert('报废数量有误,请重新输入!');
                    return;
                }
                Ajax.request({
                    url: '../sparepart/queryAll?name='+vm.sparePart.name+'&spec='+vm.sparePart.spec,
                    async: true,
                    successCallback: function (r) {
                        // console.log(r)
                        num=r.list.length
                        if(num!=0){
                            alert('该名称规格的备件清单已创建,请重新确认!');
                            return;
                        }
                    }
                });
                vm.sparePart.stockNum = vm.sparePart.initNum;//新增 库存数量=初始数量

            Ajax.request({
                url: url,
                params: JSON.stringify(vm.sparePart),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        handleError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传格式正确的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleSuccess: function (res, file) {
            this.$Loading.finish();
            iview.Message.success('文件上传成功');
            vm.sparePart.reserve2= file.response.url;
            var url = vm.sparePart.reserve2;
            if (url) vm.picUrl = url.substring((url.lastIndexOf("\/") + 1), url.length);
        },
        eyeFile: function (url) {
            if (url) {
                window.open(url);
            } else {
                alert('还未上传文件');
            }
        },
        handleSubmit1: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.save()
            });
        }

    }
});
